﻿using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using K9Nano.Dependency;
using K9Nano.Remoting;
using K9Nano.Runtime;
using K9Nano.Share;

namespace K9Nano.Authorization
{
    public class DefaultRbacChecker : IRbacChecker, IScopedDependency
    {
        protected readonly ISessionContext SessionContext;
        protected readonly IRbacManager RbacManager;
        protected readonly IApiInfo ApiInfo;

        public DefaultRbacChecker(IRbacManager rbacManager, ISessionContext sessionContext, IApiInfo apiInfo)
        {
            RbacManager = rbacManager;
            SessionContext = sessionContext;
            ApiInfo = apiInfo;
        }

        public virtual async ValueTask<bool> ValidateAsync(IApiResource resource, CancellationToken cancellation)
        {
            // 没有显式要求角色的API，只要登录用户都可以访问
            var roles = await RbacManager.GetRolesInResourceAsync(ApiInfo.Name, resource.PrimaryId, cancellation);
            if (roles.Count == 0) return true;
            return SessionContext.Roles.Any(x => roles.Contains(x));
        }

        public bool RequireScope(string scope)
        {
            return SessionContext.Scopes.Contains(K9SharedConstants.ApiScopeAdmin) 
                   || SessionContext.Scopes.Contains(scope);
        }
    }
}